# TO DO
# * May explore an Add option to superimpose dendrograms

from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class codaDend(OWRpy): 
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # Python variables
        self.data = {}
        self.RFunctionParam_x = ''
        self.RFunctionParam_SBP = ''
        
        # Unique R variables
        self.setRvariableNames(["defaultILRbase"])
        
        # Inputs
        self.inputs.addInput('id0', 'Compositional data (acomp or rcomp)', signals.base.RMatrix, self.processx)
        self.inputs.addInput('id1', 'Sequential binary partition', signals.base.RMatrix, self.processSBP)
        
        # GUI
        box = redRGUI.base.tabWidget(self.controlArea)
        
        ## plot tab
        self.plotTab = box.createTabPage(name = "Plot",orientation='vertical')
        self.RFunctionParam_plotExtWin = redRGUI.base.checkBox(self.plotTab,  label = "Options", buttons = [('win','Plot in external window.')], orientation='horizontal')
        self.plotArea = redRGUI.plotting.redRPlot(self.plotTab, label = "CoDa Dendrogram")
        self.plotArea.resizeCheck.uncheckAll()
        self.plotArea.topArea.hide()
        
        ## options tab
        self.optionsTab = box.createTabPage(name = "Options",orientation='vertical')
        self.RFunctionParamrange_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "range:", text = '')
        self.RFunctionParamtype_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "type (boxplot or lines):", text = 'boxplot')
        self.RFunctionParamcol_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "col:", text = '')
        self.RFunctionParamlty_tree_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "lty_tree:", text = '1')
        self.RFunctionParamlwd_leaf_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "lwd_leaf:", text = '1')
        self.RFunctionParamlwd_tree_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "lwd_tree:", text = '1')
        self.RFunctionParamcol_tree_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "col_tree:", text = 'black')
        self.RFunctionParamyaxt_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "yaxt:", text = 'NULL')
        self.RFunctionParamcol_leaf_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "col_leaf:", text = 'black')
        self.RFunctionParamlty_leaf_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "lty_leaf:", text = '1')
        self.RFunctionParamxlim_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "xlim:", text = 'NULL')
        self.RFunctionParamborder_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "border:", text = 'NULL')
        self.RFunctionParamlty_tree_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "lty_tree:", text = '1')
        self.RFunctionParamadd_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "add:", text = 'FALSE')
        self.RFunctionParamylim_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "ylim:", text = 'NULL')
        self.RFunctionParambox_space_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "box_space:", text = '0.5')
        self.RFunctionParambox_pos_lineEdit = redRGUI.base.lineEdit(self.optionsTab, label = "box_pos:", text = '0')
        
        
        
        self.commit = redRCommitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignRight, 
        callback = self.commitFunction, processOnInput=True)


    def processx(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return        
        if data:
            self.RFunctionParam_x=data.getData()
            #self.commitFunction()
            myclass = self.R('class('+self.RFunctionParam_x+')')
            if myclass in ['acomp', 'rcomp']:
                self.RFunctionParam_x=data.getData()
                #self.data = data
                self.commitFunction()
            else:
                self.status.setText('Warning: Not acomp or rcomp.')
                self.RFunctionParam_x = ''
        else:
            self.RFunctionParam_x = ''

    def processSBP(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return        
        if data:
            self.RFunctionParam_SBP=data.getData()
            #self.commitFunction()
            myclass = self.R('class('+self.RFunctionParam_SBP+')')
            if myclass in ['matrix', 'data.frame', 'list']:
                self.RFunctionParam_SBP=data.getData()
                #self.data = data
                self.commitFunction()
            else:
                print 'Not data frame, matrix or list.'
                self.RFunctionParam_SBP = ''
        else:
            self.RFunctionParam_SBP = ''
            
    def commitFunction(self):
        if str(self.RFunctionParam_x) == '': return
        
        # SBP: if no SBP, create default, else import from Input
        if self.RFunctionParam_SBP == '':
            self.R('defaultSBP<-as.data.frame(gsi.ilrBase2signary(t(ilrBase('+self.RFunctionParam_x+'))))', wantType = 'NoConversion')
            self.R(self.Rvariables['defaultILRbase']+'<-gsi.buildilrBase(t(as.data.frame(defaultSBP)))')
        else:
            self.R(self.Rvariables['defaultILRbase']+'<-gsi.buildilrBase(t(as.data.frame('+str(self.RFunctionParam_SBP)+')))')
            ncolX=self.R('ncol('+str(self.RFunctionParam_x)+')')
            ncolSBP=self.R('ncol('+str(self.RFunctionParam_SBP)+')')        
            if ncolX != ncolSBP:
                self.status.setText('SBP has wrong dimensions.')
                return

        injection = []
        if str(self.RFunctionParamcol_lineEdit.text()) != '':
            string = 'col="'+str(self.RFunctionParamcol_lineEdit.text())+'"'
            injection.append(string)
        if str(self.RFunctionParamcol_leaf_lineEdit.text()) != '':
            string = 'col.leaf="'+str(self.RFunctionParamcol_leaf_lineEdit.text())+'"'
            injection.append(string)
        if str(self.RFunctionParamyaxt_lineEdit.text()) != '':
            string = 'yaxt='+str(self.RFunctionParamyaxt_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamlty_leaf_lineEdit.text()) != '':
            string = 'lty.leaf='+str(self.RFunctionParamlty_leaf_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamxlim_lineEdit.text()) != '':
            string = 'xlim='+str(self.RFunctionParamxlim_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamborder_lineEdit.text()) != '':
            string = 'border='+str(self.RFunctionParamborder_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamlty_tree_lineEdit.text()) != '':
            string = 'lty.tree='+str(self.RFunctionParamlty_tree_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamadd_lineEdit.text()) != '':
            string = 'add='+str(self.RFunctionParamadd_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamylim_lineEdit.text()) != '':
            string = 'ylim='+str(self.RFunctionParamylim_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamlwd_leaf_lineEdit.text()) != '':
            string = 'lwd.leaf='+str(self.RFunctionParamlwd_leaf_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamrange_lineEdit.text()) != '':
            string = 'range='+str(self.RFunctionParamrange_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamlwd_tree_lineEdit.text()) != '':
            string = 'lwd.tree='+str(self.RFunctionParamlwd_tree_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParamcol_tree_lineEdit.text()) != '':
            string = 'col.tree="'+str(self.RFunctionParamcol_tree_lineEdit.text())+'"'
            injection.append(string)
        if str(self.RFunctionParamtype_lineEdit.text()) != '':
            string = 'type="'+str(self.RFunctionParamtype_lineEdit.text())+'"'
            injection.append(string)
        if str(self.RFunctionParambox_space_lineEdit.text()) != '':
            string = 'box.space='+str(self.RFunctionParambox_space_lineEdit.text())+''
            injection.append(string)
        if str(self.RFunctionParambox_pos_lineEdit.text()) != '':
            string = 'box.pos='+str(self.RFunctionParambox_pos_lineEdit.text())+''
            injection.append(string)
        if injection != []:
            inj = ','.join(injection)
        else: inj = ''

        self.plotArea.plotMultiple(query = 'X='+str(self.RFunctionParam_x)+',V='+self.Rvariables['defaultILRbase']+','+inj, function = 'CoDaDendrogram')
        
        
        if 'win' in self.RFunctionParam_plotExtWin.getCheckedIds(): 
            self.R('CoDaDendrogram(X='+str(self.RFunctionParam_x)+',V='+self.Rvariables['defaultILRbase']+','+inj+')')